package com.cml.getway.core.context;

import com.cml.getway.common.enums.ResponseCode;
import com.cml.getway.common.util.JSONUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.netty.handler.codec.http.*;
import lombok.Data;
import org.asynchttpclient.Response;

/**
 * 姓名：陈茂林
 * 时间：2024/1/8
 * 描述：
 */
@Data
public class GetwayResponse {
    //	响应头
    private HttpHeaders responseHeaders = new DefaultHttpHeaders();

    //	额外的响应结果
    private final HttpHeaders extraResponseHeaders = new DefaultHttpHeaders();

    //	返回的响应内容
    private String content;

    //	返回响应状态码
    private HttpResponseStatus httpResponseStatus;

    //	响应对象
    private Response futureResponse;

    private GetwayResponse() {
    }


    public void putHeader(CharSequence key, CharSequence val) {
        responseHeaders.add(key, val);
    }


    public static GetwayResponse buildRapidResponse(Response futureResponse) {
        GetwayResponse getwayResponse = new GetwayResponse();
        getwayResponse.setFutureResponse(futureResponse);
        getwayResponse.setHttpResponseStatus(HttpResponseStatus.valueOf(futureResponse.getStatusCode()));
        return getwayResponse;
    }


    public static GetwayResponse buildRapidResponse(ResponseCode code, Object... args) {
        ObjectNode objectNode = JSONUtil.createObjectNode();
        objectNode.put(JSONUtil.STATUS, code.getStatus().code());
        objectNode.put(JSONUtil.CODE, code.getCode());
        objectNode.put(JSONUtil.MESSAGE, code.getMessage());
        GetwayResponse rapidResponse = new GetwayResponse();
        rapidResponse.setHttpResponseStatus(code.getStatus());
        rapidResponse.putHeader(HttpHeaderNames.CONTENT_TYPE,
                HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
        rapidResponse.setContent(JSONUtil.toJSONString(objectNode));
        return rapidResponse;
    }


    public static GetwayResponse buildRapidResponseObj(Object data) {
        ObjectNode objectNode = JSONUtil.createObjectNode();
        objectNode.put(JSONUtil.STATUS, ResponseCode.SUCCESS.getStatus().code());
        objectNode.put(JSONUtil.CODE, ResponseCode.SUCCESS.getCode());
        objectNode.putPOJO(JSONUtil.DATA, data);
        GetwayResponse getwayResponse = new GetwayResponse();
        getwayResponse.setHttpResponseStatus(ResponseCode.SUCCESS.getStatus());
        getwayResponse.putHeader(HttpHeaderNames.CONTENT_TYPE,
                HttpHeaderValues.APPLICATION_JSON + ";charset=utf-8");
        getwayResponse.setContent(JSONUtil.toJSONString(objectNode));
        return getwayResponse;
    }
}
